<template>
  <div class="dashboard-container">
    <!-- 页面标题 -->
    <div class="page-title">
      <el-card shadow="never">
        <div class="title-content">
          <svg-icon icon-class="dashboard" />
          <span>广电用户仪表盘</span>
          <el-button 
            type="primary" 
            icon="el-icon-refresh" 
            @click="refreshDashboard"
            :loading="loading"
            class="refresh-btn"
          >
            刷新数据
          </el-button>
        </div>
      </el-card>
    </div>

    <!-- 指标卡区域 -->
    <div class="metrics-cards">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="metric-card primary-card" shadow="hover">
            <div class="metric-content">
              <div class="metric-value">{{ dashboardData.totalUsers || 0 }}</div>
              <div class="metric-label">总用户数</div>
              <div class="metric-change" :class="{ positive: dashboardData.userGrowth > 0, negative: dashboardData.userGrowth < 0 }">
                <span>{{ dashboardData.userGrowth > 0 ? '+' : '' }}{{ dashboardData.userGrowth }}%</span>
                <span class="change-label">较上月</span>
              </div>
            </div>
            <div class="metric-icon">
              <svg-icon icon-class="user" />
            </div>
          </el-card>
        </el-col>
        
        <el-col :span="6">
          <el-card class="metric-card success-card" shadow="hover">
            <div class="metric-content">
              <div class="metric-value">{{ dashboardData.activeUsers || 0 }}</div>
              <div class="metric-label">活跃用户数</div>
              <div class="metric-rate">{{ dashboardData.activeRate || 0 }}%</div>
            </div>
            <div class="metric-icon">
              <svg-icon icon-class="active" />
            </div>
          </el-card>
        </el-col>
        
        <el-col :span="6">
          <el-card class="metric-card warning-card" shadow="hover">
            <div class="metric-content">
              <div class="metric-value">{{ dashboardData.avgConsumption || 0 }}</div>
              <div class="metric-label">平均消费水平</div>
              <div class="metric-unit">元/月</div>
            </div>
            <div class="metric-icon">
              <svg-icon icon-class="money" />
            </div>
          </el-card>
        </el-col>
        
        <el-col :span="6">
          <el-card class="metric-card danger-card" shadow="hover">
            <div class="metric-content">
              <div class="metric-value">{{ dashboardData.pendingRetention || 0 }}</div>
              <div class="metric-label">待挽留用户</div>
              <div class="metric-urgency">需紧急处理</div>
            </div>
            <div class="metric-icon">
              <svg-icon icon-class="warning" />
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 图表区域 -->
    <div class="charts-area">
      <!-- 第一行图表 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-card shadow="hover">
            <template #header>
              <div class="card-header">
                <span>用户业务品牌分布</span>
              </div>
            </template>
            <div class="chart-container">
              <div id="businessBrandChart" ref="businessBrandChart"></div>
            </div>
          </el-card>
        </el-col>
        
        <el-col :span="12">
          <el-card shadow="hover">
            <template #header>
              <div class="card-header">
                <span>用户价值等级分布</span>
              </div>
            </template>
            <div class="chart-container">
              <div id="userValueChart" ref="userValueChart"></div>
            </div>
          </el-card>
        </el-col>
      </el-row>
      
      <!-- 第二行图表 -->
      <el-row :gutter="20" style="margin-top: 20px;">
        <el-col :span="12">
          <el-card shadow="hover">
            <template #header>
              <div class="card-header">
                <span>电视消费水平分布</span>
              </div>
            </template>
            <div class="chart-container">
              <div id="tvConsumeChart" ref="tvConsumeChart"></div>
            </div>
          </el-card>
        </el-col>
        
        <el-col :span="12">
          <el-card shadow="hover">
            <template #header>
              <div class="card-header">
                <span>宽带消费水平分布</span>
              </div>
            </template>
            <div class="chart-container">
              <div id="broadbandConsumeChart" ref="broadbandConsumeChart"></div>
            </div>
          </el-card>
        </el-col>
      </el-row>
      
      <!-- 第三行图表 -->
      <el-row :gutter="20" style="margin-top: 20px;">
        <el-col :span="24">
          <el-card shadow="hover">
            <template #header>
              <div class="card-header">
                <span>用户增长趋势</span>
              </div>
            </template>
            <div class="chart-container large-chart">
              <div id="growthTrendChart" ref="growthTrendChart"></div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import { getDashboardData } from "@/api/media/dashboard";
import * as echarts from "echarts";

export default {
  name: "MediaUserDashboard",
  data() {
    return {
      loading: false,
      dashboardData: {
        totalUsers: 0,
        activeUsers: 0,
        activeRate: 0,
        avgConsumption: 0,
        pendingRetention: 0,
        userGrowth: 0,
        businessBrandData: [],
        userValueData: [],
        tvConsumeData: [],
        broadbandConsumeData: [],
        growthTrendData: []
      },
      charts: {}
    };
  },
  mounted() {
    // 初始化加载数据
    this.loadDashboardData();
    // 设置自动刷新（每10分钟）
    this.autoRefreshTimer = setInterval(() => {
      this.loadDashboardData();
    }, 10 * 60 * 1000);
  },
  beforeDestroy() {
    // 清理定时器和图表实例
    if (this.autoRefreshTimer) {
      clearInterval(this.autoRefreshTimer);
    }
    this.destroyCharts();
  },
  methods: {
    // 刷新仪表盘
    refreshDashboard() {
      this.loadDashboardData();
    },
    
    // 加载仪表盘数据
    async loadDashboardData() {
      this.loading = true;
      try {
        const response = await getDashboardData();
        if (response.code === 200) {
          this.dashboardData = response.data;
          // 渲染图表
          this.renderCharts();
        } else {
          this.$message.error("加载数据失败：" + response.msg);
        }
      } catch (error) {
        this.$message.error("加载数据失败，请稍后重试");
        console.error("加载仪表盘数据错误:", error);
      } finally {
        this.loading = false;
      }
    },
    
    // 渲染所有图表
    renderCharts() {
      this.renderBusinessBrandChart();
      this.renderUserValueChart();
      this.renderTvConsumeChart();
      this.renderBroadbandConsumeChart();
      this.renderGrowthTrendChart();
    },
    
    // 渲染业务品牌分布饼图
    renderBusinessBrandChart() {
      const chartDom = this.$refs.businessBrandChart;
      if (!chartDom) return;
      
      if (!this.charts.businessBrandChart) {
        this.charts.businessBrandChart = echarts.init(chartDom);
      }
      
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left'
        },
        series: [
          {
            name: '业务品牌',
            type: 'pie',
            radius: '60%',
            data: this.dashboardData.businessBrandData || [],
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      };
      
      this.charts.businessBrandChart.setOption(option);
    },
    
    // 渲染用户价值等级分布饼图
    renderUserValueChart() {
      const chartDom = this.$refs.userValueChart;
      if (!chartDom) return;
      
      if (!this.charts.userValueChart) {
        this.charts.userValueChart = echarts.init(chartDom);
      }
      
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left'
        },
        series: [
          {
            name: '用户价值',
            type: 'pie',
            radius: ['40%', '70%'],
            data: this.dashboardData.userValueData || [],
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      };
      
      this.charts.userValueChart.setOption(option);
    },
    
    // 渲染电视消费水平柱状图
    renderTvConsumeChart() {
      const chartDom = this.$refs.tvConsumeChart;
      if (!chartDom) return;
      
      if (!this.charts.tvConsumeChart) {
        this.charts.tvConsumeChart = echarts.init(chartDom);
      }
      
      const data = this.dashboardData.tvConsumeData || [];
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        xAxis: {
          type: 'category',
          data: data.map(item => item.name)
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            data: data.map(item => item.value),
            type: 'bar',
            showBackground: true,
            backgroundStyle: {
              color: 'rgba(180, 180, 180, 0.2)'
            }
          }
        ]
      };
      
      this.charts.tvConsumeChart.setOption(option);
    },
    
    // 渲染宽带消费水平柱状图
    renderBroadbandConsumeChart() {
      const chartDom = this.$refs.broadbandConsumeChart;
      if (!chartDom) return;
      
      if (!this.charts.broadbandConsumeChart) {
        this.charts.broadbandConsumeChart = echarts.init(chartDom);
      }
      
      const data = this.dashboardData.broadbandConsumeData || [];
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        xAxis: {
          type: 'category',
          data: data.map(item => item.name)
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            data: data.map(item => item.value),
            type: 'bar',
            showBackground: true,
            backgroundStyle: {
              color: 'rgba(180, 180, 180, 0.2)'
            }
          }
        ]
      };
      
      this.charts.broadbandConsumeChart.setOption(option);
    },
    
    // 渲染用户增长趋势线图
    renderGrowthTrendChart() {
      const chartDom = this.$refs.growthTrendChart;
      if (!chartDom) return;
      
      if (!this.charts.growthTrendChart) {
        this.charts.growthTrendChart = echarts.init(chartDom);
      }
      
      const data = this.dashboardData.growthTrendData || [];
      const option = {
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['新增用户', '总用户数']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: data.map(item => item.month)
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '新增用户',
            type: 'line',
            stack: '总量',
            data: data.map(item => item.newUsers || 0)
          },
          {
            name: '总用户数',
            type: 'line',
            stack: '总量',
            data: data.map(item => item.totalUsers || 0)
          }
        ]
      };
      
      this.charts.growthTrendChart.setOption(option);
    },
    
    // 销毁所有图表实例
    destroyCharts() {
      Object.values(this.charts).forEach(chart => {
        if (chart && chart.dispose) {
          chart.dispose();
        }
      });
      this.charts = {};
    }
  }
};
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
}

.page-title {
  margin-bottom: 20px;
}

.title-content {
  display: flex;
  align-items: center;
  font-size: 18px;
  font-weight: bold;
}

.title-content .svg-icon {
  margin-right: 10px;
}

.refresh-btn {
  margin-left: auto;
}

.metrics-cards {
  margin-bottom: 20px;
}

.metric-card {
  height: 150px;
  display: flex;
  position: relative;
  overflow: hidden;
  transition: all 0.3s ease;
}

.metric-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

.metric-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  padding: 0 20px;
}

.metric-value {
  font-size: 32px;
  font-weight: bold;
  color: #fff;
  margin-bottom: 5px;
}

.metric-label {
  font-size: 16px;
  color: rgba(255, 255, 255, 0.9);
  margin-bottom: 5px;
}

.metric-change,
.metric-rate,
.metric-unit,
.metric-urgency {
  font-size: 14px;
  color: rgba(255, 255, 255, 0.8);
}

.metric-change.positive {
  color: #52c41a;
}

.metric-change.negative {
  color: #ff4d4f;
}

.change-label {
  margin-left: 5px;
}

.metric-icon {
  width: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: rgba(255, 255, 255, 0.5);
  font-size: 48px;
}

.primary-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.success-card {
  background: linear-gradient(135deg, #66bb6a 0%, #43a047 100%);
}

.warning-card {
  background: linear-gradient(135deg, #ffa726 0%, #fb8c00 100%);
}

.danger-card {
  background: linear-gradient(135deg, #ef5350 0%, #e53935 100%);
}

.chart-container {
  height: 300px;
  width: 100%;
}

.large-chart {
  height: 400px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
  color: #333;
}
</style>